package code

import (
	"fmt"
	"os"
	"path/filepath"
	"starry_sky/internal/tools"
	"text/template"
)

var TemplateMap = make(map[string]*template.Template)

func InitTemplate() error {
	rootPath := "template/code"

	modelFuncMap := template.FuncMap{
		"AttributeAnnotation": AttributeAnnotation,
		"StructAnnotation":    StructAnnotation,
		"TableName":           tools.CamelToSnake,
	}
	modelPath := filepath.Join(rootPath, "model.code")
	modelBuf, err := os.ReadFile(modelPath)
	if err != nil {
		return err
	}
	TemplateMap["model"] = template.Must(template.New("model").Funcs(modelFuncMap).Parse(string(modelBuf)))
	daoPath := filepath.Join(rootPath, "dao.code")
	daoBuf, err := os.ReadFile(daoPath)
	if err != nil {
		return err
	}
	TemplateMap["dao"] = template.Must(template.New("dao").Parse(string(daoBuf)))
	serviceFuncMap := template.FuncMap{
		"LowerFirst": tools.LowerFirst,
	}
	servicePath := filepath.Join(rootPath, "service.code")
	serviceBuf, err := os.ReadFile(servicePath)
	TemplateMap["service"] = template.Must(template.New("service").Funcs(serviceFuncMap).Parse(string(serviceBuf)))
	return nil
}

func AttributeAnnotation(s string) string {
	return "// " + s
}

func StructAnnotation(structName string, StructDesc string) string {
	return fmt.Sprintf("// %s %s", structName, StructDesc)
}
